#!/usr/bin/env bash
set -Eeo pipefail

USER="$(id -u)"

if [ -z "$(ls -A "/home/openresty/instance")" ]; then
    mkdir -p /home/openresty/instance/conf
    mkdir -p /home/openresty/instance/logs
    mkdir -p /home/openresty/instance/html
    cat <<EOF > /home/openresty/instance/conf/nginx.conf
#user  nobody;
#worker_processes  1;

# Enables the use of JIT for regular expressions to speed-up their processing.
pcre_jit  on;

error_log  logs/error.log;

#pid  logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /usr/local/openresty/nginx/conf/mime.types;
    default_type  application/octet-stream;

    # Enables or disables the use of underscores in client request header fields.
    # When the use of underscores is disabled, request header fields whose names contain underscores are marked as invalid and become subject to the ignore_invalid_headers directive.
    # underscores_in_headers off;

    log_format  main  '\$remote_addr - \$remote_user [\$time_local] "\$request" '
                      '\$status \$body_bytes_sent "\$http_referer" '
                      '"\$http_user_agent" "\$http_x_forwarded_for"';
    access_log  logs/access.log  main;

    # Log in JSON Format
    # log_format nginxlog_json escape=json '{ "timestamp": "\$time_iso8601", '
    # '"remote_addr": "\$remote_addr", '
    #  '"body_bytes_sent": \$body_bytes_sent, '
    #  '"request_time": \$request_time, '
    #  '"response_status": \$status, '
    #  '"request": "\$request", '
    #  '"request_method": "\$request_method", '
    #  '"host": "\$host",'
    #  '"upstream_addr": "\$upstream_addr",'
    #  '"http_x_forwarded_for": "\$http_x_forwarded_for",'
    #  '"http_referrer": "\$http_referer", '
    #  '"http_user_agent": "\$http_user_agent", '
    #  '"http_version": "\$server_protocol", '
    #  '"nginx_access": true }';
    # access_log logs/access.log nginxlog_json;

    client_body_temp_path ngx_client_body;
    proxy_temp_path       ngx_proxy;
    fastcgi_temp_path     ngx_fastcgi;
    uwsgi_temp_path       ngx_uwsgi;
    scgi_temp_path        ngx_scgi;

    sendfile  on;
    #tcp_nopush     on;

    keepalive_timeout  65;
    
    #gzip  on;

    server {
        listen       8080;
        server_name  localhost;
        charset      utf-8;

        location / {
            default_type text/html;
            content_by_lua_block {
                ngx.say("<html><head><title>OpenResty running...</title></head><body><h1>hello, world!</h1></body></html>")
            }
        }
    }
}
EOF
fi

if [ "$USER" -eq 0 ]; then
    chown -R openresty:openresty /home/openresty/instance/
fi

exec gosu openresty "$@"
